// pages2/pages/mall/activityDetail/index.js

import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
import { clearShopCartStorage } from '../../../../utils/hooks';
const $api = require('../../../../request/api').API;
const colorContainer = ['#07C160', '#1989FA', '#8148AD', '#FF9FB7', '#FF976A'];
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    content: '',
    activity: null, //传过来的活动内容
    downNums: 0,
    upNums: 0,
    viewNums: 0,
    type: 0, //1表示已经点赞 2表示已经踩
    menuBtnTop: app.globalData.menuBtnTop,
    btnList: [],
    buyType: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    this.setData({
      activity: JSON.parse(decodeURIComponent(options.params))
    });
    this.getData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},
  back() {
    wx.navigateBack({
      delta: 1
    });
  },
  // 阻止冒泡
  stopBubble() {},
  // 获取数据
  async getData() {
    const res = await $api.getActivityDetil({ id: this.data.activity.activityId });
    let { downNums, upNums, content, viewNums } = res.data.data;
    const reg = /<a.*?<\/a>/gm; // 这里正则的匹配一定要注意*要使用惰性匹配，否则匹配的</a>就不是以一个了
    const reg2 = /\(s.d\)/gm;
    const arr = content.match(reg) || []; //匹配到的所以a标签
    const splitlist = content.split(/<a/);
    const styleArr = []; //按钮样式列表
    let str = '';
    arr.forEach(item => {
      if (reg2.test(item)) {
        // 存在按钮样式
        str = item.match(reg2)[0].replace(/\(s|d\)/g, '');
        styleArr.push('btn' + str);
      } else {
        // 不存在按钮样式
        styleArr.push('.default-btn');
      }
    });
    content = '';
    splitlist.forEach((item, index) => {
      if (index) {
        content = content + '<a class=' + styleArr[index - 1] + item;
      } else {
        content = item;
      }
    });
    content = content.replace(reg2, '');
    let type = 0;
    if (downNums < 0) {
      downNums = Math.abs(downNums);
      type = 2;
    } else if (upNums < 0) {
      upNums = Math.abs(upNums);
      type = 1;
    }
    this.setData({
      type,
      downNums,
      upNums,
      content,
      viewNums
    });
    console.log(viewNums, 104);
    this.getBtnList();
  },
  async clickActions(e) {
    let {
      activity: { activityId },
      type,
      downNums,
      upNums
    } = this.data;
    if (type) return;
    type = e.currentTarget.dataset.type;
    await $api.activityClickActions({ id: activityId, type: type + 1 });
    this.setData({
      type,
      downNums: type == 2 ? ++downNums : downNums,
      upNums: type == 1 ? ++upNums : upNums
    });
  },
  // 获取按钮列表
  async getBtnList() {
    let res = await $api.listChildBtn({ activityId: this.data.activity.activityId });
    res = res.data.data;
    res.forEach((item, index) => (item.color = colorContainer[index]));
    this.setData({
      btnList: res
    });
  },
  // 点击按钮
  async clickBtn(e) {
    const { btnName, activityServerId } = e.currentTarget.dataset.item;
    const { activity } = this.data;
    const { activityType, activityId, buyWay, beeperId, addressType, btnId, btnType, classifyIds, queryType, linkUrl } =
      activity;
    let res = null;
    if (activityType == 1) {
      Toast.loading({
        message: '正在加载中',
        forbidClick: true,
        mask: true
      });
      res = await $api.getGoodsByBtn({ activityServerId, beeperId });
      const { goods, addressInfo, attr } = res.data.data;
      if (buyWay == 13 || buyWay == 14) clearShopCartStorage();
      const buyType = {
        eventId: buyWay,
        beeperId,
        id: btnId,
        btnType,
        classifyIds,
        queryType,
        btnName,
        linkUrl,
        orderSource: 5,
        sourceId: activityId,
        attr
      };
      // 这里的orderSource为5表示活动下单
      buyType.goods = { ...goods, nums: 1 };
      buyType.addressInfo = { ...addressInfo, addressType };
      this.setData({
        buyType
      });
      Toast.clear();
    } else if (activityType == 2) {
      await Dialog.confirm({
        title: '提示',
        message: '确定修改为' + btnName + '？',
        zIndex: '10'
      });
      res = await $api.setActivityRecord({ activityId, btnName });
      res = res.data.data;
      Toast.success('操作成功');
      const page = getCurrentPages().find(item => item.route == 'subcontract/home/pages/activity/index');
      page.data.list.find(item => item.activityId == activityId && (item.selectedName = btnName));
      page.setData({
        list: page.data.list
      });
    }
  },
  handleTagATap(e) {
    console.log(e);
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
});
